using Domain;
using MediatR;
using SqlSugar;
using System;
using System.Threading;
using System.Threading.Tasks;
using WriteAPI.Command.采购;

namespace WriteAPI.CommandHandle.采购
{
    public class CreateCgddCommandHandler : IRequestHandler<CreateCgddCommand, int>
    {
        private readonly ISqlSugarClient _db;

        public CreateCgddCommandHandler(ISqlSugarClient db)
        {
            _db = db;
        }

        public async Task<int> Handle(CreateCgddCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 开启事务
                int cgddId = 0;
                
                // 使用事务
                _db.Ado.BeginTran();
                
                try
                {
                    // 创建采购订单主体
                    var cgdd = new Lwp_Cgdd
                    {
                        OrderTheme = request.OrderTheme,
                        PurchaseNumber = request.SystemNumber ? GenerateSystemNumber() : request.PurchaseNumber,
                        SystemNumber = request.SystemNumber ? "1" : "0",
                        RelatedPurchase = request.RelatedPurchase,
                        RelatedSalesOrder = request.RelatedSalesOrder,
                        UnbindSalesOrder = request.UnbindSalesOrder,
                        PurchaseDate = request.PurchaseDate,
                        SupplierName = request.SupplierName,
                        ContactPerson = request.ContactPerson,
                        Purchaser = request.Purchaser,
                        ContactPhone = request.ContactPhone,
                        ContactMethod = request.ContactMethod,
                        SettlementMethod = request.SettlementMethod,
                        PurchaseDepartment = request.PurchaseDepartment,
                        RelatedProject = request.RelatedProject,
                        DeliveryAddress = request.DeliveryAddress,
                        Remarks = request.Remarks,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    };

                    // 插入采购订单主体
                    cgddId = await _db.Insertable(cgdd).ExecuteReturnIdentityAsync();

                    // 插入采购订单明细项
                    foreach (var item in request.CgddItems)
                    {
                        var cgddItem = new Lwp_CgddItem
                        {
                            OrderId = cgddId,
                            ItemCode = item.ItemCode,
                            ItemName = item.ItemName,
                            Spec = item.Spec,
                            Unit = item.Unit,
                            Brand = item.Brand,
                            Quantity = item.Quantity,
                            TaxRate = item.TaxRate,
                            TaxPrice = item.TaxIncludedPrice,
                            TaxAmount = item.TotalWithTax,
                            UntaxedPrice = item.PriceWithoutTax,
                            UntaxedAmount = item.AmountWithoutTax,
                            DeliveryDate = item.DeliveryDate ?? DateTime.Now,
                            MainUnitQuantity = item.MainUnitQuantity,
                            Progress = item.Progress,
                            Remarks = item.Remark,
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now
                        };

                        await _db.Insertable(cgddItem).ExecuteCommandAsync();
                    }

                    // 提交事务
                    _db.Ado.CommitTran();
                }
                catch (Exception ex)
                {
                    // 回滚事务
                    _db.Ado.RollbackTran();
                    throw;
                }

                return cgddId;
            }
            catch (Exception ex)
            {
                throw new Exception($"创建采购订单失败: {ex.Message}");
            }
        }

        // 生成系统编号
        private string GenerateSystemNumber()
        {
            var date = DateTime.Now;
            var year = date.Year;
            var month = date.Month.ToString().PadLeft(2, '0');
            var day = date.Day.ToString().PadLeft(2, '0');
            var random = new Random().Next(1000, 10000).ToString();
            return $"CG{year}{month}{day}{random}";
        }
    }
} 